<template>
  <el-dialog
    :title="isUpdate?'修改项目':'新增项目'"
    :visible.sync="visible"
    :before-close="close"
    append-to-body
    :close-on-click-modal="false"
    width="100%">

    <div>说明：您可以将以下数据<span v-if="!isUpdate">(示例数据)</span>
      <el-button type="text" :loading="downloadExcelLoading" @click="downloadExcel">
        导出为Excel
      </el-button>，然后在Excel内编辑，但是
      <span style="color: red">不能修改表头，以及前两列(ID、PARENT_ID列)</span>
      ，编辑完成后导入到下方编辑区再次进行编辑，之后便可导入系统
    </div>

    <div style="color: red;">注：分类 和 检验组 属于系统内置选项，请填写时务必对应系统内置选项，否则导入后为空白，您也可以
      <el-button type="text" :loading="downloadcagLoading" @click="downloadCategoryAndGroup">
        导出系统内置选项
      </el-button>
    </div>

    <el-divider>以下为编辑区</el-divider>

    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />

    <el-table :data="tableData" border fit highlight-current-row style="margin-top:20px;">
      <el-table-column label="ID" align="center" min-width="70">
        <template slot-scope="scope">
          {{ scope.row.inspectionItemId }}
        </template>
      </el-table-column>
      <el-table-column label="PARENT_ID" align="center" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.parentId }}
        </template>
      </el-table-column>
      <el-table-column label="排序号" align="center" min-width="100">
        <template slot-scope="scope">
          <el-input size="mini" type="textarea" autosize v-model="scope.row.orderId" placeholder="排序号"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" min-width="100">
        <template slot-scope="scope">
          <el-select
            filterable
            v-model="scope.row.inspectionCategoryId"
            placeholder="分类"
            style="width: 100%"
            size="mini">
            <el-option
              v-for="category in categoryList"
              :key="category.inspectionCategoryId"
              :label="category.inspectionCategoryName"
              :value="category.inspectionCategoryId">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="检验组" align="center" min-width="110">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.inspectionGroupId"
            placeholder="检验组"
            style="width: 100%"
            size="mini">
            <el-option
              v-for="group in groupList"
              :key="group.inspectionGroupId"
              :label="group.inspectionGroupName"
              :value="group.inspectionGroupId">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="项名称" align="center" min-width="110">
        <template slot-scope="scope">
          <el-input size="mini" type="textarea" autosize v-model="scope.row.inspectionItemName" placeholder="项名称"></el-input>
        </template>
      </el-table-column>
<!--      <el-table-column label="是否用于打印" align="center" width="70">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isPrint"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1">
          </el-switch>
        </template>
      </el-table-column> -->
     <el-table-column label="打印别名" align="center" min-width="110">
        <template slot-scope="scope">
          <el-input size="mini" type="textarea" autosize v-model="scope.row.printItemName" placeholder="打印别名"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="国家标准值" align="center" min-width="200">
        <template slot-scope="scope">
          <el-input size="mini" type="textarea" :autosize="{minRows: 5, maxRows: 5}" v-model="scope.row.nationInspectionItemValue" placeholder="国家标准值"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="内部标准值" align="center" min-width="200">
        <template slot-scope="scope">
          <el-input size="mini" type="textarea" :autosize="{minRows: 5, maxRows: 5}" v-model="scope.row.insideInspectionItemValue" placeholder="内部标准值"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="含有化学式" align="center" width="90">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.haveFormulaValue"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否数值结果" align="center" width="90">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isNumber"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1">
          </el-switch>
        </template>
      </el-table-column>
<!--      <el-table-column label="是否半年检一次" align="center" width="90">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isHalfYearTest"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1">
          </el-switch>
        </template>
      </el-table-column> -->
<!--      <el-table-column label="标准值是否显示应符合规定" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.printValue"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column> -->
<!--      <el-table-column label="检验结果是否显示符合规定" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.printConfig"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column> -->
<!--      <el-table-column label="标准工时1" align="center" width="85">
        <template slot-scope="scope">
          <el-input size="mini" type="textarea" autosize v-model="scope.row.manHourOne" placeholder="标准工时1"></el-input>
        </template>
      </el-table-column> -->
<!--      <el-table-column label="标准工时2" align="center" width="85">
        <template slot-scope="scope">
          <el-input size="mini" type="textarea" autosize v-model="scope.row.manHourTwo" placeholder="标准工时2"></el-input>
        </template>
      </el-table-column> -->
<!--      <el-table-column label="标准下限" align="center" width="85">
        <template slot-scope="scope">
          <el-input size="mini" type="textarea" autosize v-model="scope.row.insideInspectionItemDownValue" placeholder="标准下限"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="标准上限" align="center" width="85">
        <template slot-scope="scope">
          <el-input size="mini" type="textarea" autosize v-model="scope.row.insideInspectionItemUpValue" placeholder="标准上限"></el-input>
        </template>
      </el-table-column> -->
      <el-table-column label="标准限值单位" align="center" width="105">
        <template slot-scope="scope">
          <el-input size="mini" type="textarea" autosize v-model="scope.row.insideInspectionItemValueUnit" placeholder="标准限值单位"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="warning" class="pan-btn warning-btn" icon="el-icon-plus" @click="addItem(scope.$index)" circle size="mini" />
          <el-button type="danger" class="pan-btn danger-btn" icon="el-icon-minus" @click="subItem(scope.$index)" circle size="mini" />
        </template>
      </el-table-column>
    </el-table>

    <span slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" class="pan-btn primary-btn" @click="submit">确 定</el-button>
  	</span>
  </el-dialog>
</template>

<script>
  import UploadExcelComponent from '@/components/UploadExcel/index.vue'
  import { isBlank } from '@/common/js/utils'
  import { CODE_OK } from '@/common/js/config'
  import { getGroupList,getCategorysList } from '@/api/inspection'
  import { export_json_to_excel } from '@/common/js/Export2Excel'
  export default {
    data() {
      return {
        isUpdate: false,
        visible: false,
        exItem: {
          orderId: 1,
          inspectionCategoryId: 3,
          inspectionCategoryName: '检查',
          inspectionGroupId: 11,
          inspectionGroupName: '仪器组',
          inspectionItemName: '有关物质(单杂)',
          isPrint: 0,
          printItemName: '有关物质',
          nationInspectionItemValue: null,
          insideInspectionItemValue: '供试品溶液色谱图中如有杂质峰,单个杂质峰面积不得大于对照溶液主峰面积的0.3倍(0.3%)。',
          haveFormulaValue: 1,
          isNumber: 0,
          isHalfYearTest: 1,
          printValue: 0,
          printConfig: 0,
          manHourOne: '3.5',
          manHourTwo: '1',
          insideInspectionItemDownValue: null,
          insideInspectionItemUpValue: '0.3',
          insideInspectionItemValueUnit: '%'
        },
        tableData: [],
        tableHeader: [],
        groupList: [],
        categoryList: [],
        grandDataForm: {},
        downloadExcelLoading: false,
        addExcelFilename: '项目导入示例模板',
        updateExcelFilename: '项目修改',
        excelAutoWidth: true,
        excelBookType: 'xlsx',
        cagList: [],
        downloadcagLoading: false,
        cagFilename: '分类和检验组',
        cagAutoWidth: true,
        cagBookType: 'xlsx'
      }
    },
    components: { UploadExcelComponent },
    created() {
      this.visible = true
      this.getStandardInfo()
      if (this.childDataForm.isUpdate) {
        this.tableData = this.childDataForm.list
        this.isUpdate = true
      }else{
        this.tableData.push(JSON.parse(JSON.stringify(this.exItem)))
      }
    },
    props: ["childDataForm"],
    methods: {
      addItem(i) {
        let newItem = JSON.parse(JSON.stringify(this.tableData[i]))
        if (newItem.inspectionItemId) {
          newItem.inspectionItemId = null
        }
        if (newItem.parentId) {
          newItem.parentId = null
        }
        this.tableData.splice(i+1,0,newItem)
      },
      subItem(i) {
        if (this.tableData.length == 1) {
          this.$message.error('请保留至少一个项目')
          return
        }
        this.tableData.splice(i,1)
      },
      downloadCategoryAndGroup() {
        this.downloadcagLoading = true
        if (!isBlank(this.categoryList) && !isBlank(this.groupList)) {
          this.cagList.push(...this.groupList.map(v => {
            this.$set(v, 'inspectionCategoryName', null)
            return v
          }))
          this.cagList.push(...this.categoryList.map(v => {
            this.$set(v, 'inspectionGroupName', null)
            return v
          }))
          const tHeader = [
            '检验组',
            '分类'
          ]
          const filterVal = ['inspectionGroupName', 'inspectionCategoryName']
          const list = this.cagList
          const data = this.formatJson(filterVal, list)
          export_json_to_excel({
            header: tHeader,
            data,
            filename: this.cagFilename,
            autoWidth: this.cagAutoWidth,
            bookType: this.cagBookType
          })
          this.downloadcagLoading = false
        }else{
          setTimeout(() => {
            this.downloadCategoryAndGroup()
          }, 500)
        }
      },
      downloadExcel() {
        this.downloadExcelLoading = true
        const tHeader = [
          'ID',
          'PARENT_ID',
          '排序号',
          '分类',
          '检验组',
          '项名称',
          '是否用于打印',
          '打印别名',
          '国家标准值',
          '内部标准值',
          '含有化学式',
          '是否数值结果',
          '是否半年检一次',
          '标准值是否显示应符合规定',
          '检验结果是否显示符合规定',
          '标准工时1',
          '标准工时2',
          '标准下限',
          '标准上限',
          '标准限值单位'
        ]
        const filterVal = [
          'inspectionItemId',
          'parentId',
          'orderId',
          'inspectionCategoryName',
          'inspectionGroupName',
          'inspectionItemName',
          'isPrint',
          'printItemName',
          'nationInspectionItemValue',
          'insideInspectionItemValue',
          'haveFormulaValue',
          'isNumber',
          'isHalfYearTest',
          'printValue',
          'printConfig',
          'manHourOne',
          'manHourTwo',
          'insideInspectionItemDownValue',
          'insideInspectionItemUpValue',
          'insideInspectionItemValueUnit'
        ]
        const list = this.tableData.map(v => {
          v.isPrint = this.num2Str(v.isPrint)
          v.haveFormulaValue = this.num2Str(v.haveFormulaValue)
          v.isNumber = this.num2Str(v.isNumber)
          v.isHalfYearTest = this.num2Str(v.isHalfYearTest)
          v.printValue = this.num2Str2(v.printValue)
          v.printConfig = this.num2Str2(v.printConfig)
          return v
        })
        const data = this.formatJson(filterVal, list)
        export_json_to_excel({
          header: tHeader,
          data,
          filename: this.isUpdate ? this.updateExcelFilename : this.addExcelFilename,
          autoWidth: this.excelAutoWidth,
          bookType: this.excelBookType
        })
        this.downloadExcelLoading = false
      },
      num2Str(num) {
        return num == 0 ? '是' : '否'
      },
      num2Str2(num) {
        return num == 1 ? '是' : '否'
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          return v[j]
        }))
      },
      beforeUpload(file) {
        const isLt1M = file.size / 1024 / 1024 < 1
        if (isLt1M) {
          return true
        }
        this.$message({
          message: '导入的excel最大为1M',
          type: 'warning'
        })
        return false
      },
      getStandardInfo () {
        const params = {
          page: 1,
          limit: 9999999
        }
      	getGroupList(params).then(res => {
      		if (res.code === CODE_OK) {
      			this.groupList = res.page.list.filter(g => {
              return g.inspectionGroupId != 1 && g.inspectionGroupId != 2
            })
            this.$set(this.grandDataForm,'groupList',this.groupList)
      		}else{
            this.$message.error(res.msg)
          }
      	})
      	getCategorysList(params).then(res => {
      		if (res.code === CODE_OK) {
      			this.categoryList = res.page.list
            this.$set(this.grandDataForm,'categoryList',this.categoryList)
      		}else{
            this.$message.error(res.msg)
          }
      	})
      },
      handleSuccess({ results, header }) {
        this.tableData = results.map(v => {
          // 如果此标准是更新，那么才保留原id，否则为新增，则不能保留原id
          let id = null,parentId = null
          if (this.isUpdate) {
            id = v.ID
            parentId = v.PARENT_ID
          }
          this.$set(v,'inspectionItemId',id)
          this.$set(v,'parentId',parentId)
          this.$set(v,'orderId',v.排序号)
          this.$set(v,'inspectionCategoryName',v.分类)
          this.$set(v,'inspectionCategoryId',null)
          let category = this.categoryList.find(x => x.inspectionCategoryName == v.inspectionCategoryName)
          if (!isBlank(category)) {
            v.inspectionCategoryId = category.inspectionCategoryId
          }
          this.$set(v,'inspectionGroupName',v.检验组)
          this.$set(v,'inspectionGroupId',null)
          let group = this.groupList.find(x => x.inspectionGroupName == v.inspectionGroupName)
          if (!isBlank(group)) {
            v.inspectionGroupId = group.inspectionGroupId
          }
          this.$set(v,'inspectionItemName',v.项名称)
          this.$set(v,'isPrint',v.是否用于打印 == '是' ? 0 : 1)
          this.$set(v,'printItemName',v.打印别名)
          this.$set(v,'nationInspectionItemValue',v.国家标准值)
          this.$set(v,'insideInspectionItemValue',v.内部标准值)
          this.$set(v,'haveFormulaValue',v.含有化学式 == '是' ? 0 : 1)
          this.$set(v,'isNumber',v.是否数值结果 == '是' ? 0 : 1)
          this.$set(v,'isHalfYearTest',v.是否半年检一次 == '是' ? 0 : 1)
          this.$set(v,'printValue',v.标准值是否显示应符合规定 == '是' ? 1 : 0)
          this.$set(v,'printConfig',v.检验结果是否显示符合规定 == '是' ? 1 : 0)
          this.$set(v,'manHourOne',v.标准工时1)
          this.$set(v,'manHourTwo',v.标准工时2)
          this.$set(v,'insideInspectionItemDownValue',v.标准下限)
          this.$set(v,'insideInspectionItemUpValue',v.标准上限)
          this.$set(v,'insideInspectionItemValueUnit',v.标准限值单位)
          return v
        })
        this.tableHeader = header
      },
      submit() {
        if (this.formVerify()) {
          this.tableData = this.tableData.map(v => {
            this.$set(v,'waterQuantityId',null)
            this.$set(v,'waterQuantityName',null)
            this.$set(v,'groupNum',null)
            this.$set(v,'edit',false)
            return v
          })
          this.close('submit')
        }
      },
      formVerify() {
        let itemNames = []
        for (let i = 0,j = this.tableData.length; i < j; i++) {
          let n,e = JSON.parse(JSON.stringify(this.tableData[i]))
          if (isBlank(n = e.inspectionItemName)) {
            this.$message.error('检验项目名称不能为空')
            return false
          }
          if (itemNames.indexOf(n) > -1) {
            this.$message.error("为保证检验台帐质量,检验项名称不能重复,请修改："+n)
            return false
          }
          if (isBlank(e.inspectionGroupId)) {
            this.$message.error('所属小组不能为空')
            return false
          }
          if (isBlank(e.inspectionCategoryId)) {
            this.$message.error('所属分类不能为空')
            return false
          }
          itemNames.push(n)
        }
        return true
      },
      close(val) {
        this.$emit('close')
        if (val == 'submit') {
          this.$emit('getItems', this.tableData)
        }
        this.visible = false
      }
    }
  }
</script>

<style scoped>
</style>
